import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:getwidget/getwidget.dart';
import 'package:intl/intl.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:pitchertools/common/extensions/datetime_extension.dart';
import 'package:pitchertools/dao/data_manager.dart';
import 'package:pitchertools/http/dio_http.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
import 'package:velocity_x/velocity_x.dart';

import '../../../../models/fans_query_bean.dart';
import '../../index.dart';

class UpdateQueryFansMsgDialog extends GetView<QueryFansController> {
  UpdateQueryFansMsgDialog({required this.selectedIndex, super.key}) {}
  // 选中的索引
  final int selectedIndex;

  final controller = Get.find<QueryFansController>();

  /// 构建下拉菜单
  buildDropdownMenuItems(FansQueryBean selecedFansQueryBean) {
    List fansQueryApiMsgs = controller.state.fansQueryApiMsgsRx.value;
    var selectedFansQueryApiMsg = null;

    // print(fansQueryApiList);

    List<DropdownMenuItem> dropdownMenuItems = [];

    for (var i = 0; i < fansQueryApiMsgs.length; i++) {
      var item = DropdownMenuItem(
        value: fansQueryApiMsgs[i],
        child: Text(fansQueryApiMsgs[i]['queryApiName']),
      );
      dropdownMenuItems.add(item);
      if (selecedFansQueryBean.queryApiUrl ==
          fansQueryApiMsgs[i]['queryApiUrl']) {
        controller.state.selectedFansQueryApiMsg = fansQueryApiMsgs[i];
        selectedFansQueryApiMsg = controller.state.selectedFansQueryApiMsg;
      }
    }

    return Obx(() {
      return Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.black, width: 1.0),
          borderRadius: BorderRadius.circular(4.0),
        ),
        child: DropdownButton(
          value: selectedFansQueryApiMsg['queryApiName'] == null
              ? null
              : controller.state.selectedFansQueryApiMsg,
          onChanged: (newValue) {
            //设置查询api
            controller.state.selectedFansQueryApiMsg = newValue;
            // print(newValue);
            // print(newValue.runtimeType);
          },
          items: dropdownMenuItems,
          hint: const Text("请选择查询类型"),
          underline: Container(),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    List fansQueryBeans = controller.state.fansQueryBeanListRx;
    FansQueryBean selecedFansQueryBean = fansQueryBeans[selectedIndex];

    final TextEditingController csNumberTEC =
        TextEditingController(text: selecedFansQueryBean.csNumber);
    final TextEditingController startDateTEC =
        TextEditingController(text: selecedFansQueryBean.startDate);
    final TextEditingController endDateTEC =
        TextEditingController(text: selecedFansQueryBean.endDate);

    final PickerDateRange selectedDateRange = PickerDateRange(
      DateTime.parse(selecedFansQueryBean.startDate),
      DateTime.parse(selecedFansQueryBean.endDate),
    );

    final DateRangePickerController dateRangePC = DateRangePickerController();

    return AlertDialog(
      title: const Text('修改查询').center(),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          //设置间隔为8
          children: [
            15.heightBox,
            GFTextField(
              controller: csNumberTEC,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                labelText: "客服号",
              ),
            ),
            10.heightBox,
            buildDropdownMenuItems(selecedFansQueryBean),
            10.heightBox,
            SizedBox(
              height: 250,
              width: 250,
              child: SfDateRangePicker(
                view: DateRangePickerView.month,
                selectionMode: DateRangePickerSelectionMode.range,
                initialSelectedRange: selectedDateRange,
                controller: dateRangePC,
                onSelectionChanged: (dateRangePickerSelectionChangedArgs) {
                  if (dateRangePickerSelectionChangedArgs.value
                      is PickerDateRange) {
                    PickerDateRange pickerDateRange =
                        dateRangePickerSelectionChangedArgs.value;

                    if (pickerDateRange.startDate == null) {
                      startDateTEC.text = "";
                    } else {
                      startDateTEC.text =
                          pickerDateRange.startDate!.formatDateYYMMDD_HHMMSS();
                    }
                    if (pickerDateRange.endDate == null) {
                      endDateTEC.text = "";
                    } else {
                      endDateTEC.text = pickerDateRange.endDate!
                          .endOfToday()
                          .formatDateYYMMDD_HHMMSS();
                    }
                  }
                },
              ),
            ),
            10.heightBox,
            GFTextField(
              controller: startDateTEC,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                labelText: "开始时间",
              ),
            ),
            10.heightBox,
            GFTextField(
              controller: endDateTEC,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                labelText: "结束时间",
              ),
            ),
          ],
        ),
      ),
      actions: <Widget>[
        TextButton(
          child: const Text('确定'),
          onPressed: () async {
            Navigator.of(context).pop();
            // 获取客服号
            String csNumber = csNumberTEC.text.trim();
            String startDateStr = startDateTEC.text.trim();
            String endDateStr = endDateTEC.text.trim();
            if (csNumber.isEmpty ||
                startDateStr.isEmpty ||
                endDateStr.isEmpty) {
              SmartDialog.showToast("客服号、开始时间、结束时间不能为空");
              return;
            }

            // 获取设置的查询api
            var selectedFansQueryApi = controller.state.selectedFansQueryApiMsg;

            if (selectedFansQueryApi['queryApiName'] == null) {
              SmartDialog.showToast("请选择查询类型");
              return;
            }

            var fansQueryBean = FansQueryBean(
              csNumber: csNumber,
              queryApiType: selectedFansQueryApi['queryApiType'] == "HaiWang"
                  ? FansQueryApiType.HaiWang
                  : FansQueryApiType.DaMai,
              queryApiUrl: selectedFansQueryApi['queryApiUrl'],
              queryApiName: selectedFansQueryApi['queryApiName'],
              startDate: startDateStr,
              endDate: endDateStr,
            );

            controller.state.fansQueryBeanListRx[selectedIndex] = fansQueryBean;

            SmartDialog.showToast("修改成功");
          },
        ),
        TextButton(
          child: const Text('取消'),
          onPressed: () async {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }
}
